<?php
/**
 * ==============================================
 * Copy right 2015-2016 http://wei.meididi88.com
 * ----------------------------------------------
 * This is not a free software, without any authorization is not allowed to use and spread.
 * ==============================================
 * @author: hy
 * @date: 2015-9-10
 * @version: v1.0.0
 */
namespace Common\Model;

use Think\Model;

/**
 * 服务步骤、产品描述内容Model模型类
 */
class ContentModel extends Model{
	
	protected $_auto = array(
		array('created','time',1,'function'), //新增时
	);
	
	/**
	 * @param number $targetId	服务项目、产品编号
	 * @return boolean|array
	 */
	public function getTargetContent($targetId) {
		$steps = S('Step_'.$targetId);
		if (!$steps) {
			$steps = $this->where(array('target_id' => $targetId, 'status' => 1))->select();
			S('Step_'.$targetId, $steps);
		}
		
		return $steps;
	}
	
	/**
	 * 编辑内容
	 * 
	 * @param number $targetId	服务项目、产品编号
	 * @param array $contents	内容
	 * @param array $titles		标题
	 * @return boolean
	 */
	public function editContent($targetId, $ids, $contents, $titles) {
		$steps = D('Content')->getTargetContent($targetId);
		$stepIds = array();
		if (!is_array($steps)) {
			$steps = array();
		}
		
		if ($steps) {
			$stepIds = array_map(function ($var) {
				return $var ['id'];
			}, $steps);
		}
		
		$conbineContent = array();
		if ($contents) {
			foreach ($contents as $key => $value) {
				$contentData = array(
					'title' => isset($titles [$key])?$titles [$key]:'',
					'content' => $value
				);
				
				if ($stepIds && isset($ids [$key]) && $ids [$key]) {
					$index = array_search($ids [$key], $stepIds);
					if ($index !== false ) {
						unset($steps [$index]);
						$this->where(array('id' => $ids [$key]))->save($contentData);
					} else {
						$contentData ['target_id'] = $targetId;
						$contentData ['created'] = time();
						$stepAddResult = $this->add($contentData);
						if (!$stepAddResult) {
							
							return false;
						}
					}
				} else {
					$contentData ['target_id'] = $targetId;
					$contentData ['created'] = time();
					$stepAddResult = $this->add($contentData);
					if (!$stepAddResult) {
						return false;
					}
				}
			}
			
			S('Step_'.$targetId, NULL);
		}
		
		if ($steps) {
			foreach ($steps as $key => $value) {
				if (!$this->where(array('id' => $value ['id']))->delete()) {
					return false;
				}
			}
		}
		
		return true;
	}
}